package com.sbtr.controller;

import com.alibaba.fastjson.JSONObject;
import com.sbtr.business.project.service.IProjectService;
import com.sbtr.business.trainingmodel.service.ITrainingModelDataService;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.open.project.dto.ProjectDto;
import com.sbtr.open.project.dto.ProjectSearchDto;
import com.sbtr.open.trainingmodel.dto.TrainingModelDataDto;
import com.sbtr.overview.dto.AllCountDto;
import com.sbtr.overview.dto.MaterialSetTypeCountDto;
import com.sbtr.overview.dto.ModelTypeCountDto;
import com.sbtr.overview.dto.ProjectRateCountDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 系统模型管理 前端控制器
 * </p>
 *

 */
@RestController
@RequestMapping("/project")
@Api(tags = "模型管理模块（包含模型的增删改查功能等）")
public class ProjectController {
	
	@Autowired
	private IProjectService projectService;

	@Autowired
	private ITrainingModelDataService trainingModelDataService;


	@ApiOperation(value = "查询所有", notes = "查询所有", httpMethod = "GET")
	@RequestMapping(value = "/overview/all", method = RequestMethod.GET)
	public Response<AllCountDto> getAllCount(@RequestParam("creater")String creater) {
		return Response.success(projectService.getAllCount(creater));
	}

	@ApiOperation(value = "查询项目状态数量", notes = "查询所有", httpMethod = "GET")
	@RequestMapping(value = "/overview/project", method = RequestMethod.GET)
	public Response<List<ProjectRateCountDto>> getProjectRateCount(@RequestParam("creater")String creater) {
		return Response.success(projectService.getProjectRateCount(creater));
	}

	@ApiOperation(value = "查询模型分类数量", notes = "查询所有", httpMethod = "GET")
	@RequestMapping(value = "/overview/training-model", method = RequestMethod.GET)
	public Response<List<ModelTypeCountDto>> getModelTypeCount(@RequestParam("creater")String creater) {
		return Response.success(projectService.getModelTypeCount(creater));
	}

	@ApiOperation(value = "查询素材类型数量", notes = "查询所有", httpMethod = "GET")
	@RequestMapping(value = "/overview/material-set", method = RequestMethod.GET)
	public Response<List<MaterialSetTypeCountDto>> getMaterialSetTypeCount(@RequestParam("creater")String creater) {
		return Response.success(projectService.getMaterialSetTypeCount(creater));
	}

	@ApiOperation(value = "根据id集合批量删除", notes = "根据id集合批量删除", httpMethod = "DELETE")
	@RequestMapping(value = "batch", method = RequestMethod.DELETE)
	public Response<Boolean> batchDeleteById(@RequestParam("idList") List<Long> idList){
		boolean b = projectService.batchDeleteById(idList);
		if(b){
			return Response.success("删除成功", b);
		}else{
			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败");
		}
	}

	@ApiOperation(value = "新的分页查询", notes = "新的分页查询", httpMethod = "POST")
	@PostMapping(value = "search-page")
	public Response<PageDto<ProjectDto>> searchPage(@RequestBody ProjectSearchDto dto, HttpServletRequest request){
		String algorithmUserId = request.getHeader("algorithmUserId");

		dto.setBelonger(algorithmUserId);
		return Response.success(projectService.searchPage(dto));
	}

	@ApiOperation(value = "获取项目类型", notes = "获取项目类型", httpMethod = "GET")
	@GetMapping(value = "/get-project-type")
	public Response<List<String>> getProjectType(){
		return Response.success(projectService.getProjectType());
	}

	@ApiOperation(value = "获取使用模型算法名称", notes = "获取使用模型算法名称", httpMethod = "GET")
	@GetMapping(value = "/get-algorithm-name")
	public Response<List<String>> getAlgorithmName(){
		return Response.success(projectService.getAlgorithmName());
	}


	
	@ApiOperation(value = "根据id查找", notes = "根据id查找", httpMethod = "GET")
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Response<ProjectDto> findById(@PathVariable("id") Long id){

		return Response.success(projectService.findById(id));
	}
	
	@ApiOperation(value = "根据id删除", notes = "根据id删除", httpMethod = "DELETE")
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	public Response<Boolean> deleteById(@PathVariable("id") Long id){
		boolean b = projectService.deleteById(id);
		if(b){
			return Response.success("删除成功", b);
		}else{
			return Response.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "删除失败");
		}
	}

//	@ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "POST")
//	@PostMapping(value = "search")
//	public Response<PageDto<ProjectDto>> search(@RequestBody ProjectSearchDto dto){
//		return Response.success(projectService.search(dto));
//	}

	@ApiOperation(value = "保存项目信息", notes = "保存", httpMethod = "POST")
	@RequestMapping(value = "", method = RequestMethod.POST)
	public Response<ProjectDto> save(@RequestBody ProjectDto dto, HttpServletRequest request){
		if(dto.getId() == null){
			String algorithmUserId = request.getHeader("algorithmUserId");
//			dto.setCreater(UserUtils.getFdLoginName());
			dto.setBelonger(algorithmUserId);
			dto.setCreateTime(new Date());
			return Response.success("保存成功", projectService.save(dto));
		} else {
//			dto.setModifyer(UserUtils.getFdLoginName());
			return Response.success("修改成功", projectService.update(dto));
		}
	}
	
	@ApiOperation(value = "对接工业云查询项目接口", notes = "对接工业云查询项目接口", httpMethod = "POST")
	@PostMapping(value = "search-by-creater")
	public Response<PageDto<ProjectDto>> searchByCreater(@RequestBody ProjectSearchDto dto){
		return Response.success(projectService.searchByCreater(dto));
	}
	
//	@ApiOperation(value = "根据用户id上线模型信息", notes = "根据用户id上线模型信息", httpMethod = "GET")
//	@GetMapping("search-model-by-userid")
//	public Response<List<ProjectModelDto>> searchModelByUserId(@RequestParam("userId")String userId){
//		return Response.success(projectService.searchModelByUserId(userId));
//	}


	@ApiOperation(value = "根据项目id查找获取无监督结果文件", notes = "根据项目id查找获取无监督结果文件", httpMethod = "GET")
	@RequestMapping(value = "/{id}/getResultFile", method = RequestMethod.GET)
	@ResponseBody
	public void getResultFile(@PathVariable("id") Long id,
							 HttpServletResponse resp
	) {

		OutputStream out;
		// 读取本地文件的输入流

		InputStream in;
		File file;
		try {
			TrainingModelDataDto model = trainingModelDataService.findModelByProject(id);
			String result = model.getEvaluate();
			JSONObject jsObj = JSONObject.parseObject(result);
			String resultFile = jsObj.getString("file_path");
			String objectName=resultFile.substring(resultFile.lastIndexOf("/")+1,resultFile.length());
			file=new File(resultFile);
			in = new FileInputStream(file);
			// 设置响应正文的MIME类型
//			resp.setContentType("Content-Disposition;charset=UTF-8");
			resp.setContentType("application/octet-stream");

			resp.setHeader("Content-Disposition", "attachment;" + " filename=" + objectName);
			// 把本地文件发送给客户端
			out = resp.getOutputStream();
			int byteRead = 0;
			byte[] buffer = new byte[512];
			while ((byteRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, byteRead);
			}
			in.close();
			out.flush();
			out.close();
		}catch (Exception e){
			e.printStackTrace();
		}


//		return Response.success(publishPredictTaskApi.getResultUrl(id));
	}
}
